package com.kx.hackathon.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kx.hackathon.service.HandlerService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

@Service("TranslateServiceImpl")
public class TranslateServiceImpl implements HandlerService {
    @Autowired
    OkHttpClient httpClient;
    private final String appId = "20211031000987562";
    private final String password = "TSDOMStS7OHevreE6JfU";
    private final Pattern chinaPattern = Pattern.compile("[\u4e00-\u9fa5]");
    private String translate(String word) throws IOException {
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = DigestUtils.md5DigestAsHex((appId + word + salt + password).getBytes());
        String to = "zh";
        if(chinaPattern.matcher(word).find()) to = "en";
        String url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + word + "&from=auto&to="+to+"&appid=" + appId + "&salt="+salt+"&sign=" + sign;
        System.out.println(url);
        Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Response response = httpClient.newCall(request).execute();
        String json = null;
        if (response.body() != null) {
            json = response.body().string();
        }
        String result = json.split("\"dst\":\"")[1].split("\"")[0];
        if(to.equals("zh")) result = unicodeToCn(result);
        System.out.println(result);
        return result;

    }
    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }
    @Override
    public String handle(String msg, String arg) throws IOException {
        return translate(arg);
    }

    @Override
    public String init(String msg, String arg) {
        return null;
    }

    @Override
    public boolean needInit() {
        return false;
    }
}
